package com.samphanie.auiu.auth.validation;

import com.samphanie.auiu.auth.annotation.ValidPassword;
import com.samphanie.auiu.auth.utils.CryptoUtil;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.passay.MessageResolver;
import org.passay.PasswordData;
import org.passay.PasswordValidator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author ZSY
 * @createTime 2021/4/19 18:08
 */
@RequiredArgsConstructor
public class PasswordConstraintValidator implements ConstraintValidator<ValidPassword, String> {

    private final MessageResolver messageResolver;
    private final CryptoUtil cryptoUtil;

    @Override
    public void initialize(final ValidPassword constraintAnnotation) {

    }

    @Override
    public boolean isValid(String password, ConstraintValidatorContext context) {
        val validator = new PasswordValidator(messageResolver, cryptoUtil.getPasswordRules());
        val result = validator.validate(new PasswordData(password));

        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(String.join(
                ",", validator.getMessages(result)
        )).addConstraintViolation();

        return result.isValid();
    }


}
